﻿using AlibabaCloud.SDK.Dysmsapi20170525;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using System;
using System.Threading.Tasks;
using System.Linq;
using Easy.Cloud.Communication.Sms.Core;
using Easy.Cloud.Communication.Sms.Ali.Options;

namespace Easy.Cloud.Communication.Sms.Ali
{
    public class AliSmsClient : ISmsClient
    {
        private readonly AliOptions _option;

        public AliSmsClient(AliOptions option)
        {
            _option = option;
        }

        public async Task<ResponseMessage> SendAsync(SendRequest request)
        {
            try
            {
                var client = await CreateClient();

                var sendSmsRequest = await CreateSendSmsRequest(request);

                var response = client.SendSmsWithOptions(sendSmsRequest, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());

                if (!response.Body.Code.Equals("OK"))
                    return new ResponseMessage(false, response);

                return new ResponseMessage(true ,response);
            }
            catch (Exception e)
            {
                throw new AliException(e.Message + e.InnerException);
            }
        }

        private Task<Client> CreateClient()
        {
            var config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = _option.AccessKeyId,
                AccessKeySecret = _option.AccessKeySecret,
            };

            config.Endpoint = _option.Endpoint;

            Client client = new Client(config);

            return Task.FromResult(client);
        }


        private Task<SendSmsRequest> CreateSendSmsRequest(SendRequest request)
        {
            var signName = _option.SignNameItem.Single(s => s.Name.Equals(request.SignName));

            var template = _option.TemplateItem.Single(s => s.Name.Equals(request.Template));

            var sendSmsRequest = new SendSmsRequest()
            {
                PhoneNumbers = request.PhoneNumbers,
                SignName = signName.ToString(),
                TemplateParam = request.TemplateParam,
                TemplateCode = template.Value
            };
            return Task.FromResult(sendSmsRequest);
        }
    }
}